package com.example.raidball;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import android.content.Context;
import android.content.res.AssetManager;

public class LoadWorld {
	
	private int[] world = new int[1025];
	private File fic;
	private InputStream ins;
	private Context context;
			
	public LoadWorld(Context context) {
		this.context = context;
		
		// essai
		try {
			ins = context.getAssets().open("Maps/map1.txt");			// creer le InputStream a partir du fichier .txt
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (Exception e) {}
		
		// Chargement du fichier dans fic.
		//fic = new File("file:///android_asset/Maps/map1.txt");
		//fic = new File(context.getAssets().open("file:///android_asset/Maps/map1.txt"));
		//loadFile();
		
		/*
		try {
			Scanner loadScanner = new Scanner(fic);				// scan un File
			while(loadScanner.hasNext()) {
				// Lecture d'un fichier map World.
				for (int y=0; y<world.length;y++) {
					world[y] = loadScanner.nextInt();
				}
			}
			loadScanner.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		*/
		
		try {
			Scanner loadScanner = new Scanner(ins);				// scan un InputStream
			while(loadScanner.hasNext()) {
				// Lecture d'un fichier map World.
				for (int y=0; y<world.length;y++) {
					world[y] = loadScanner.nextInt();
				}
			}
			loadScanner.close();
		} catch (Exception e) {}
		
	}
	
	public int getCaseId(int id) {
		if (id > 1025)
			return 0;
		else
			return world[id];
	}
	
	/**
	 * doit a priori lire le ficher Maps/map1.txt dans la variable FIC
	 */
	public void loadFile() {
		FileOutputStream fos = null;
		AssetManager am = context.getAssets();
		try {
			InputStream is = am.open("Maps/map1.txt");
			int size = is.available();
			byte[] buffer = new byte[size];
			int nbread = 0;
	        fos = new FileOutputStream(fic);
	        while((nbread=is.read(buffer))>-1){
	            fos.write(buffer,0,nbread);               
	        }
	        fos.close();
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
